<template>
  <div id="email">
    <van-nav-bar title="邮箱登录" left-text="返回" left-arrow @click-left="onClickLeft" />
    <div id="content">
      <van-field v-model="email" label="邮箱" placeholder="请输入邮箱" />

      <van-field v-model="sms" center clearable label="验证码" placeholder="请输入短信验证码">
        <template #button>
          <van-button size="small" type="primary" v-if="flag" @click="startCountdown()"
            >发送验证码</van-button
          >
          <van-button size="small" type="primary" v-else @click="sendsCode()"
            >{{ s }}后重新发送</van-button
          >
        </template>
      </van-field>
      <van-button type="primary" block @click="emailLogin()">登录</van-button>
    </div>
  </div>
</template>
<script setup>
import axios from 'axios'
import { showToast } from 'vant'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const email = ref('')
const sms = ref('')
const s = ref(60)
const flag = ref(true)
const onClickLeft = () => history.back()

const startCountdown = async () => {
  if (email.value != '') {
    flag.value = !flag.value
    let timer = setInterval(() => {
      s.value--
      if (s.value == 0) {
        flag.value = !flag.value
        clearInterval(timer)
        s.value = 60
      }
    }, 1000)
    axios.post('http://localhost:3000/cj/email', { email: email.value }).then((res) => {
      if (res.data.state === 200) {
        showToast('发送成功')
        sms.value=res.data.code
      } else {
        showToast('发送失败')
      }
      console.log(res.data);
    })
  } else {
    showToast('请输入正确的邮箱')
  }
}

const sendsCode = () => {
  if (s.value != 0) {
    showToast('请等待')
  }
}

const emailLogin = async () => {
  axios.post('http://localhost:3000/cj/email',{email:email.value,codes:sms.value}).then((res)=>{
    if(res.data.state===200){
      showToast('登录成功')
  
      router.push('/home')
    }else{
      showToast('登录失败')
    }
  })
}
</script>
<style scoped>
#email {
  width: 390px;
  height: 844px;
}
#content {
  width: 100%;
  height: 200px;
  margin-top: 200px;
}
</style>